import { getToken, findUserId } from '../api/upload'
import {dataURL2Audio} from './index.js'
import base from '../api/base'
import store from '../store/index'

export const RongIMLib = require('../libs/rongyun/RongIMLib.miniprogram-1.1.2.min.js')
const RongIMClient = RongIMLib.RongIMClient

// 注册
export const register = async() => {
        const userInfo = uni.getStorageSync('USER_INFO')
        if (!userInfo) return
        const res = await getToken()
        uni.setStorageSync('TOKEN', res)
        login()
    }
    // 登录连接
const login = () => {
	RongIMLib.RongIMClient.init(base.appKey)
	setContact()
	messageListen()
	concatServe()
}

const setContact = () => {
	// 连接状态监听器
RongIMClient.setConnectionStatusListener({
    onChanged: function (status) {
        // status 标识当前连接状态
        switch (status) {
            case RongIMLib.ConnectionStatus.CONNECTED:
                console.log('链接成功');
                break;
            case RongIMLib.ConnectionStatus.CONNECTING:
                console.log('正在链接');
                break;
            case RongIMLib.ConnectionStatus.DISCONNECTED:
                console.log('断开连接');
                break;
            case RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT:
                console.log('其他设备登录');
                break;
            case RongIMLib.ConnectionStatus.DOMAIN_INCORRECT:
                console.log('域名不正确');
                break;
            case RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE:
                console.log('网络不可用');
                break;
        }
    }
	});
}
// 消息监听器
const messageListen = () => {
	RongIMClient.setOnReceiveMessageListener({
	    // 接收到的消息
	    onReceived: function (message) {
				console.log(message)
				uni.vibrateLong()
				const messageContent = {
					fromId: message.senderUserId,
					time: message.receivedTime,
					targetId: message.targetId,
					extra: message.content.extra
				}
	        // 判断消息类型
	        switch(message.messageType){
	            case RongIMClient.MessageType.TextMessage:
							try{
								const content = JSON.parse(message.content.content)
								if (content.type) {
									messageContent.content = content.url
									chatRecord(message.targetId,messageContent,'audio').receiveMessages()
								} else {
									messageContent.content = message.content.content
									chatRecord(message.targetId,messageContent,'text').receiveMessages()
								}
							}catch(e){
								//TODO handle the exception
								messageContent.content = message.content.content
								chatRecord(message.targetId,messageContent,'text').receiveMessages()
							}
	                // message.content.content => 文字内容
	                break;
	            case RongIMClient.MessageType.VoiceMessage:
									return
									console.log('语音',message)
									uni.getSystemInfo({
										success(res) {
											dataURL2Audio(message.content.content, (entry) => {
												const path = entry.fullPath;
												messageContent.path = path
												chatRecord(message.targetId,messageContent,'audio').receiveMessages()
											}, res.platform)
										}
									})
	                break;
	            case RongIMClient.MessageType.ImageMessage:
									messageContent.content = message.content.content
									messageContent.url = message.content.imageUri
									chatRecord(message.targetId,messageContent,'img').receiveMessages()
	                // message.content.content => 图片缩略图 base64
	                // message.content.imageUri => 原图 URL
	                break;
	            case RongIMClient.MessageType.LocationMessage:
	                // message.content.latiude => 纬度
	                // message.content.longitude => 经度
	                // message.content.content => 位置图片 base64
	                break;
	            case RongIMClient.MessageType.RichContentMessage:
	                // message.content.content => 文本消息内容
	                // message.content.imageUri => 图片 base64
	                // message.content.url => 原图 URL
	                break;
	            case RongIMClient.MessageType.InformationNotificationMessage:
	                // do something
	                break;
	            case RongIMClient.MessageType.ContactNotificationMessage:
	                // do something
	                break;
	            case RongIMClient.MessageType.ProfileNotificationMessage:
	                // do something
	                break;
	            case RongIMClient.MessageType.CommandNotificationMessage:
	                // do something
	                break;
	            case RongIMClient.MessageType.CommandMessage:
	                // do something
	                break;
	            case RongIMClient.MessageType.UnknownMessage:
	                // do something
	                break;
	            default:
	                // do something
	        }
	    }
	});
}
// 连接服务器
const concatServe = () => {
    const token = uni.getStorageSync('TOKEN')
    RongIMClient.connect(token, {
        onSuccess: function(userId) {
            console.log('Connect successfully. ' + userId);
        },
        onTokenIncorrect: function() {
					uni.removeStorageSync('TOKEN')
					console.log('token 无效');
					register()
        },
        onError: function(errorCode) {
					console.log(errorCode)
            var info = '';
            switch (errorCode) {
                case RongIMLib.ErrorCode.TIMEOUT:
                    info = '超时';
                    break;
                case RongIMLib.ConnectionState.UNACCEPTABLE_PAROTOCOL_VERSION:
                    info = '不可接受的协议版本';
                    break;
                case RongIMLib.ConnectionState.IDENTIFIER_REJECTED:
                    info = 'appkey不正确';
                    break;
                case RongIMLib.ConnectionState.SERVER_UNAVAILABLE:
                    info = '服务器不可用';
                    break;
            }
            console.log(info);
        }
    });
}

// 聊天信息处理类
class ChatRecord {
    constructor(targetId, message, type) {
			this.userInfo = JSON.parse(uni.getStorageSync('USER_INFO'))
			this.targetId = targetId
			this.message = {
				...message,
				userPhoto: this.userInfo.userPhoto,
				nickName: this.userInfo.userName,
				unread: true,
				type
			}
			this.type = type
			this.path = 'pages/chat/index'
			this.recordLength = 16 //页面展示数据条数
	}
        // 存储消息
  async getChat(info) {
		const messageList = store.getters.messageList
		const messageInfo = { // 消息
				...info
		}
		const chat = uni.getStorageSync('CHAT')
		console.log(chat)
		if (chat) {
				console.log(messageList,messageInfo)
				if (chat[this.targetId]) {
						chat[this.targetId].msgContent.push(info)
						uni.setStorageSync('CHAT', chat)
						const index = messageList.findIndex((item) => {
							return item.targetId === this.targetId
						})
						console.log(index)
						messageList[index] = messageInfo
						messageList.sort((a, b) => b.time - a.time)
						store.dispatch('chat/updateMessage', messageList)
				} else {
						chat[this.targetId] = {
										msgContent: [
												info
										]
								},
						uni.setStorageSync('CHAT', chat)
						messageList.unshift(messageInfo)
						store.dispatch('chat/updateMessage', messageList)
				}
		} else {
				const createdChat = {}
				createdChat[this.targetId] = {
						msgContent: [
								info
						]
				}
				uni.setStorageSync('CHAT', createdChat)
				messageList.push(messageInfo)
				store.dispatch('chat/updateMessage', messageList)
		}
}
// 处理消息
receiveMessages() {
    this.disposeType()
}
  // 处理当前页面数据
 currentChat() {
		const chat = uni.getStorageSync('CHAT')
		const route = getCurrentPages().pop().is
		if (route === this.path) {
				if (this.targetId === store.getters.chatTarget) {
						const history = store.getters.history
						const content = chat[this.targetId].msgContent[chat[this.targetId].msgContent.length - 1]
						history.push(content)
						store.dispatch('chat/updateHistory', history)
				}
		} else {
				return
		}
}
        // 从其他页面进入消息展示
messageShow() {
	const chat = uni.getStorageSync('CHAT')
	if (!chat[this.targetId]) {
			store.dispatch('chat/updateHistory', [])
	} else {
		const chatLength = chat[this.targetId].msgContent.length
		if (chatLength > this.recordLength) {
				store.dispatch('chat/updateHistory', chat[this.targetId].msgContent.slice(-16))
		} else {
				store.dispatch('chat/updateHistory', chat[this.targetId].msgContent)
		}
	}
}
// 历史数据展示
historyRecordShow(page) {
		const chat = uni.getStorageSync('CHAT')
		const chatLength = chat[this.targetId].msgContent.length
		const recordLength = store.getters.history.length
		console.log(chatLength, recordLength)
		if (chatLength > recordLength) {
				uni.showLoading({
						title: '历史记录加载中'
				})
				const size = page * this.recordLength
				store.dispatch('chat/updateHistory', chat[this.targetId].msgContent.slice(-size))
				setTimeout(() => {
						uni.hideLoading()
				}, 1000)
				return true
		} else {
				return false
		}
}
// 处理已读
  alreadyRead() {
		const messageList = store.getters.messageList
		const chat = uni.getStorageSync('CHAT')
		if (this.targetId === store.getters.chatTarget) {
				if (chat[this.targetId]) {
						const newChat = chat[this.targetId].msgContent.map((item) => {
								item.unread = false
								return item
						})
						chat[this.targetId].msgContent = newChat
								// 可以修改已读时间
						const index = messageList.findIndex((item) => {
								return item.targetId === this.targetId
						})
						messageList[index].unread = false
						messageList.sort((a, b) => b.time - a.time)
						uni.setStorageSync('CHAT', chat)
						store.dispatch('chat/updateMessage', messageList)
				}
		}
}
// 处理消息类型
  async disposeType() {
		const types = ['text', 'img','audio']
		switch (this.type){
			case types[2]:
				this.messageAudio()
				break;
			default:
				this.messageOther()
				break;
		}
}
// 其他信息处理
async messageOther() {
	let info
	const { extra } = this.message
	if (!extra) {
			const res = await findUserId({id: this.targetId})
			info = {
					...this.message,
					targetName: res[0].userName,
					targetPhoto: res[0].userPhoto,
			}
	} else {
			info = {
					...this.message,
					...extra
			}
	}
	this.getChat(info)
	this.currentChat()
}
// 语音信息处理
	async messageAudio() {
		const _this = this
		let info
		const { extra } = this.message
		if (!extra) {
				const res = await findUserId({id: this.targetId})
				info = {
						...this.message,
						targetName: res[0].userName,
						targetPhoto: res[0].userPhoto,
				}
		} else {
				info = {
						...this.message,
						...extra
				}
		}
		uni.downloadFile({
			url: this.message.content, //仅为示例，并非真实的资源
			success: (res) => {
					if (res.statusCode === 200) {
							uni.saveFile({
									tempFilePath: res.tempFilePath,
									success: function(e) {
										const savedFilePath = e.savedFilePath;
										info.audioUrl = savedFilePath
										_this.getChat(info)
										_this.currentChat()
									}
							});
					}
			}
		});
	}
}

export const chatRecord = (targetId, message = {}, type = 'text') => {
    return new ChatRecord(targetId, message, type)
}